package com.zhuanzhuan.dao.impl;
import com.zhuanzhuan.dao.BaseDao;
import com.zhuanzhuan.dao.UserDao;
import com.zhuanzhuan.entity.User;
import com.zhuanzhuan.vo.GoodsDetail;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoMySQLImpl extends BaseDao implements UserDao {

    //通过用户名和密码获取用户信息
    @Override
    public User getUserByNameAndPwd(String name, String pwd) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        conn = getConnection();
        try {
            //构造PreparedStatement对象
            String sql = "SELECT * FROM user WHERE name=? AND password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, pwd);

            rs = pstmt.executeQuery();
            //验证用户名和密码
            if(rs.next()){
                //从MySQL读取用户信息，并加载到user对象中
                user = new User();
                user.setName(name);
                user.setId(rs.getInt("id"));
                user.setBalance(rs.getFloat("balance"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭数据库连接
            closeAll(conn, pstmt, rs);
        }
        return user;
    }

    //增加余额
    @Override
    public int addBalance(int userID, float change){
        //构造SQL语句
        String preparedSQL = "UPDATE user SET balance=balance+? WHERE id=?";
        //构造SQL执行参数数组
        List<Object> params = new ArrayList<Object>();
        params.add(change);
        params.add(userID);

        //调用BaseDao中的更新
        return exceuteUpdate(preparedSQL, params.toArray());
    }

    //减少余额
    @Override
    public int minusBalance(int userID, float change){
        //构造SQL语句
        String preparedSQL = "UPDATE user SET balance=balance-? WHERE id=?";
        //构造SQL执行参数数组
        List<Object> params = new ArrayList<Object>();
        params.add(change);
        params.add(userID);

        //调用BaseDao中的更新
        return exceuteUpdate(preparedSQL, params.toArray());
    }
}
